package com.system.xingzhi.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.system.xingzhi.annotation.LoginToken;
import com.system.xingzhi.annotation.PassToken;
import com.system.xingzhi.model.ReturnData;
import com.system.xingzhi.model.User;
import com.system.xingzhi.service.UserService;
import com.system.xingzhi.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class AuthenticationInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                             Object object) throws Exception {
        String token = httpServletRequest.getHeader("token");
        //如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //检查是否有LoginToken注解，有则验证token
        if (method.isAnnotationPresent(LoginToken.class)) {
            LoginToken loginToken = method.getAnnotation(LoginToken.class);
            if (loginToken.required()) {

                JwtUtil jwtUtil = new JwtUtil();
                String id = httpServletRequest.getHeader("id");
                User user = userService.selectByPrimaryKey(id);
                Map<String, String> map = jwtUtil.verifyToken(token, user);
                //验证token是否失效
                if (map.get("status").equals("验证成功")) {
                    return true;
                } else {
                    ReturnData returnData = new ReturnData();
                    returnData.setCode(1);
                    returnData.setDetail(map.get("status"));
                    PrintWriter writer = null;
                    httpServletResponse.setCharacterEncoding("UTF-8");
                    httpServletResponse.setContentType("text/html;charset=utf-8");
                    try {
                        writer = httpServletResponse.getWriter();
                        //使用jackson将对象转换成json
                        ObjectMapper mapper = new ObjectMapper();
                        String json = mapper.writeValueAsString(returnData);
                        writer.write(json);
                        return false;
                    } catch (IOException e) {
                        logger.info("拦截器返回信息失败");
                    } finally {
                        if (writer != null) {
                            writer.close();
                        }
                    }
                }

            }
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        String id = httpServletRequest.getHeader("id");
        httpServletResponse.setHeader("newToken","jssjisjisjsijsi");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }

}
